package com.yc.thread.wait;

public class ObjectWait2 {

	public static void main(String[] args) throws InterruptedException {

		Object b = new Object();
		Object c = new Object();

		new Thread(new BuyFood(b, c)).start();
		Thread.sleep(1000);
		new Thread(new CookFood(b, c)).start();
	}
}
/**
 * 整体思路：
 * 用两个锁，两层锁
 * 两个线程同时跑，一个线程跑完后释放完两个锁（并且是执行完需要执行的东西之后才释放完）
 * 并且在释放第二个锁的地方等待，等待多久由另外一个线程决定，所以第二个释放锁的方式就选择wait就是最好的办法
 * @author yuancan
 *
 */
class BuyFood implements Runnable {

	private Object block;

	private Object clock;

	public BuyFood(Object block, Object clock) {
		this.block = block;
		this.clock = clock;
	}

	@Override
	public void run() {

		for (int i = 0; i < 10; i++) {
			synchronized (clock) {//------------1
				// 得到买的锁
				synchronized (block) {//------------2
					p("买萝卜" + i);//------------3
					block.notify();//?什么作用，唤醒锁。但目前block还没有处于等待//------------4
				}//释放B//------------5
				try {
					clock.wait();//被迫释放C，并且暂停//------------6
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

			try {
				Thread.sleep(1000);//------------11
			} catch (InterruptedException e) {//------------12
				e.printStackTrace();
			}
		}

	}

	private void p(String s) {
		System.out.println(s);
	}

}

class CookFood implements Runnable {

	private Object block;

	private Object clock;

	public CookFood(Object block, Object clock) {
		this.block = block;
		this.clock = clock;
	}

	@Override
	public void run() {

		for (int i = 0; i < 10; i++) {

			synchronized (block) {//------------7
				// 得到买的锁
				synchronized (clock) {//------------8
					p("煮萝卜" + i);//------------9
					clock.notify();//B线程继续------------10
				}//是否C
				try {
					block.wait();//被迫释放B，并且暂停------------11
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private void p(String s) {
		System.out.println(s);
	}

}